module.exports = app => {
  const express = require('express')
  const router = express.Router({
    mergeParams: true
  })
  /*======================== 定义接口以及方法 start ========================*/
  let result = {
    code: 200,
    msg: "请求成功"
  }
  // 创建数据
  router.post('/addTeammemberInfo', (req, res) => {
    req.ModelData.create(req.body)
    res.json({ ...result })
  })
  // 获取数据
  router.get('/getTeammemberInfo', async (req, res) => {
    const model = await req.ModelData.find().limit()
    res.json({ ...result, data: model })
  })
  // 获取管理员所管理的所有项目
  router.post('/getProjects', async (req, res) => {
    const managerProjects = req.body;

    const teammemberInfo = require("../models/Teammember")

    teammemberInfo.find(
      { projectName: managerProjects }
    )
      .then(allProjects => {
        res.json(allProjects)
      })
  })
  // 修改数据
  router.post('/editTeammemberInfo', async (req, res) => {
    const teammemberInfo = require("../models/Teammember")

    const projectName = req.body.projectName
    const position = req.body.position.trim();
    const uuid = req.body.uuid
    const value = req.body.value

    let modifiedData;

    await teammemberInfo.find(
      {
        projectName
      }
    )
      .then(r => {
        const data = r[0]
        const workProgress = data.teammembers[position].workProgress

        const createUuid = () => {
          return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function (c) {
            var r = Math.random() * 16 | 0,
              v = c == 'x' ? r : (r & 0x3 | 0x8);
            return v.toString(16);
          });
        }

        const modify = (workProgress, uuid) => {
          workProgress.forEach(work => {
            if (work.uuid == uuid) {
              work.chidren.unshift({
                uuid: createUuid(),
                title: value,
                finished: false,
                fold: false,
                chidren: []
              })
              return;
            }
            else if (work.uuid != uuid && work.chidren.length != 0) {
              modify(work.chidren, uuid)
            }
          });
        }

        modify(workProgress, uuid)

        modifiedData = data;
      })
      .catch(e => {
        console.log(e);
      })

    teammemberInfo.findOneAndUpdate(
      {
        projectName
      },
      {
        [`teammembers.${position}.workProgress`]: modifiedData.teammembers[position].workProgress
      },
      {},
      (e) => {
        if (e) {
          console.log("ERROR");
          console.warn(e);
        }
      }
    )

  })
  // 删除数据
  router.post('/deleteTeammemberInfo', (req, res) => {
    req.ModelData.findByIdAndDelete(req.body._id, req.body)
    res.json({ ...result })
  })
  /*======================== 定义接口以及方法 end ========================*/

  const resourceMiddleWare = async (req, res, next) => {
    req.ModelData = await require(`../models/${req.params.resource}`) // 给请求绑定原型的名称并引入数据库原型,
    next()
  }
  app.use('/api/rest/:resource', resourceMiddleWare, router)
}